<script setup lang='ts' name="company-org">
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'

import { delCompanyOrg, getCompanyOrg, useGetCatTypeDictInfo } from '@fl/api/iam-api'
import ButtonItem from '@fl/components/button-item.vue'
import { formatTime } from '@fl/utils'
import { ElButton, ElCard, ElCol, ElDatePicker, ElForm, ElFormItem, ElInput, ElRow, ElTag } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import type { IRowV0 } from './types'

import AddUser from './component/add-user.vue'
import DetailItem from './component/detail.vue'
import { LevelDict, StewardDict } from './constant'
import { useDicts } from './hooks/use-dicts'
import { useTable } from './hooks/use-table'

const { useDict } = useDicts()

const { addBtn, btns, gridOptions } = useTable()

const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
])

const state = {
    catTypeId: [],
    createTime: '',
    createdName: '',
    // enterpriseAccount: '',
    enterpriseId: '',
    enterpriseName: '',
    legalRepresentative: '',
}

const form = ref({ ...state })

const { data: CatType } = useGetCatTypeDictInfo()

const router = useRouter()

const detail = ref<any>({})
const show = ref(true)
// const showId = ref('')
const detailItemRef = ref()
const showAdd = ref(false)
const showId = ref('')
const xGrid = ref<VxeGridInstance<IRowV0>>()

const gridEvents: VxeGridListeners<IRowV0> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getData()
    },
}

async function getData(currentPage?: any, pageSize?: any) {
    if (currentPage && pageSize) {
        gridOptions.pagerConfig.currentPage = currentPage
        gridOptions.pagerConfig.pageSize = pageSize
    }

    gridOptions.loading = true
    getCompanyOrg({
        ...form.value,
        catTypeId: form.value.catTypeId.sort().join(','),
        endTime: formatTime(form.value.createTime[1], 'yyyy-MM-dd HH:mm:ss'),
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
        startTime: formatTime(form.value.createTime[0], 'yyyy-MM-dd HH:mm:ss'),
    }).then((res: any) => {
        console.log('index', res)
        const data = res.rows ?? []
        gridOptions.loading = false

        gridOptions.pagerConfig.total = res.total
        gridOptions.data = data
    })
}

function reset() {
    form.value = { ...state }
    getData()
}

async function doAction(item: any, row: any) {
    console.log('doAction', row)
    switch (item.value) {
        case 'edit':
            router.push(`/business-management/edit-enterprise?id=${row.id}`)
            break
        case 'view':
            show.value = false
            showId.value = String(row.id)
            break
        case 'delete':
            delCompanyOrg(String(row.id)).then((res) => {
                if (res.code === 200) {
                    ElMessage.success('操作成功')
                    setTimeout(() => {
                        getData(1, 10)
                    }, 500)
                }
            })
            break
        case 'organization':
            router.push(`/business-management/personnel-organizational?id=${row.enterpriseId}&enterpriseObjectID=${row.enterpriseObjectID}&catTypeId=${row.catTypeId}`)
            break
        case 'add':
            detail.value = cloneDeep(row)
            showAdd.value = true
            showId.value = String(row.id)
            break
        default:
            break
    }
}

function doAdd() {
    router.push('/business-management/add-enterprise')
}

function toggleAllCheckboxEvent() {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleAllCheckboxRow()
}

function toggleCheckboxEvent(row) {
    const $grid = xGrid.value
    if ($grid)
        $grid.toggleCheckboxRow(row)
}

watch(show, (val: boolean) => {
    if (val)
        reset()
})

getData()
</script>

<template>
    <template v-if="show">
        <ElCard mb-20>
            <ElForm :inline="true"
                    :model="form"
                    label-width="100"
                    class="query_form"
            >
                <ElRow>
                    <ElCol :span="12">
                        <ElFormItem label="添加时间区间">
                            <ElDatePicker v-model="form.createTime"
                                          :default-time="defaultTime"
                                          type="daterange"
                                          range-separator="-"
                                          format="YYYY/MM/DD"
                                          start-placeholder="开始日期"
                                          end-placeholder="结束日期"
                            />
                        </ElFormItem>
                    </ElCol>

                    <ElCol :span="4"
                           :offset="8"
                           style="text-align: right;"
                    >
                        <ElButton type="primary"
                                  @click="getData(1, 10)"
                        >
                            搜索
                        </ElButton>

                        <ElButton @click="reset">
                            重置
                        </ElButton>
                    </ElCol>
                </ElRow>

                <ElFormItem label="企业号">
                    <ElInput v-model="form.enterpriseId"
                             placeholder="请输入"
                             clearable
                    />
                </ElFormItem>

                <ElFormItem label="企业名称">
                    <ElInput v-model="form.enterpriseName"
                             placeholder="请输入"
                             clearable
                    />
                </ElFormItem>

                <ElFormItem label="添加人">
                    <ElInput v-model="form.createdName"
                             placeholder="请输入"
                             clearable
                    />
                </ElFormItem>

                <!-- <ElFormItem label="企业管理员">
                    <ElInput v-model="form.enterpriseAccount"
                             placeholder="请输入"
                             clearable
                    />
                </ElFormItem> -->

                <ElFormItem label="企业法人">
                    <ElInput v-model="form.legalRepresentative"
                             placeholder="请输入"
                             clearable
                    />
                </ElFormItem>

                <ElFormItem label="业务类别">
                    <ElSelect v-model="form.catTypeId"
                              collapse-tags
                              collapse-tags-tooltip
                              multiple
                    >
                        <ElOption v-for="item in CatType"
                                  :key="item.value"
                                  :value="item.value"
                                  :label="item.label"
                        />
                    </ElSelect>
                </ElFormItem>
            </ElForm>
        </ElCard>

        <ElCard>
            <div class="mb-20">
                <ElButton type="primary"
                          @click="doAdd"
                >
                    + 添加企业
                </ElButton>
            </div>
            <!-- 列表 -->
            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      v-on="gridEvents"
            >
                <template #checkbox_header="{ checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleAllCheckboxEvent"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #checkbox_cell="{ row, checked, indeterminate }">
                    <span class="custom-checkbox"
                          @click.stop="toggleCheckboxEvent(row)"
                    >
                        <i v-if="indeterminate"
                           class="vxe-icon-square-minus-fill"
                        />

                        <i v-else-if="checked"
                           class="vxe-icon-square-checked-fill"
                        />

                        <i v-else
                           class="vxe-icon-checkbox-unchecked"
                        />
                    </span>
                </template>

                <template #enterpriseLevelId="{ row }">
                    <div class="flex gap-2">
                        <ElTag :type=" row?.enterpriseLevelId === LevelDict['一级企业'] ? 'warning' : 'success'">
                            {{ row.enterpriseLevel }}
                        </ElTag>
                    </div>
                </template>

                <template #status="{ row }">
                    {{ useDict('EnterpriseStatus', row.status) }}
                </template>

                <template #cooperationType="{ row }">
                    {{ useDict('CooperationType', row.cooperationType) }}
                </template>

                <template #operate="{ row }">
                    <!-- 新：0房交会业务但没新增管理员 1房交会业务已有管理员 null非房交会业务 -->
                    <ButtonItem :btns=" (row?.steward === StewardDict['房交会无管理员'] && row?.enterpriseLevelId === LevelDict['二级企业']) ? [...btns, addBtn] : btns "
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>
        </ElCard>
    </template>

    <DetailItem v-else
                ref="detailItemRef"
                v-model="show"
                :show-id="showId"
                @confirm="getData"
    />

    <AddUser v-if="showAdd"
             key="add"
             v-model="showAdd"
             :show-id="showId"
             :data="detail"
             @confirm="getData"
    />
</template>

<style lang="less" scoped>
.query_form {
    :deep(.el-form-item__content) {
        width: 250px;
    }
}
</style>
